// websocket.js
import {
    bindChat
} from "@/api/chat.js"
import store from '@/store'
import playMp3 from "@/utils/play_ding.js"

let reconnectTimer = null;
let socket = null;
let isConnected = false;
let isReconnecting = false;
let isLogOut = false //是否退出
export default {
    // 连接 WebSocket
    connectWebSocket() {
        // 创建 WebSocket 连接
        socket = uni.connectSocket({
             url: 'wss://betayl.weilankangyang.com/wss',
            success: () => {
                console.log('WebSocket 连接成功666');
            },
            fail: (err) => {
                console.error('WebSocket 连接失败:', err);
            }
        });
        uni.onSocketMessage((res) => {
            console.log(res, "接收信息")

            if (res.data.includes("'")) {
                const response = JSON.parse(res.data.replace(/'/g, '"'));
                if (response.type === 'init') {
                    // 处理初始化消息
                    uni.setStorageSync('client_id', response.client_id)
                    if (uni.getStorageSync("token")) {
                        this.bindChatIfNeeded()
                    }
                }
            } else if (res.data.includes("content")) {
                const data = JSON.parse(res.data);
                console.log(data, "666")
                store.commit('updateReceiveMsg', data); //更新消息
                store.commit('UPDATE_CHATLIST', data); //更新chatlist
                playMp3.play_ding('https://yl.weilankangyang.com/static/mini_program/dingdong.mp3', 3000)
            } else if (res.data.includes("serviceOrdersPayment")) {
                const data = JSON.parse(res.data);
                console.log(data, "666")
                store.commit('updateReceivePush', data);
            }
            // console.log(123)
            // 推送消息结构
            // let data1 = {
            //     data: {
            //         order_no: '10022023102697569910',
            //         pay_price: '100.00',
            //         service_name: '擦玻璃测试',
            //         service_time: '2023-10-26 15:44:57'
            //     },
            //     tips: "您有新的服务订单支付，请尽快处理！",
            //     type: "serviceOrdersPayment"
            // }
            // store.commit('updateReceivePush', data1);
        });
        // 监听 WebSocket 连接打开事件
        uni.onSocketOpen(() => {
            console.log('WebSocket 连接已打开');
            this.isConnected = true; // 标记连接已打开
        });

        // 监听 WebSocket 连接关闭事件
        uni.onSocketClose(() => {
            console.log('WebSocket 连接已关闭');
            if (!this.isReconnecting) {
                this.reconnectWebSocket(); // 在非重连状态下执行重连
            }
        });

        // 监听 WebSocket 连接出错事件
        uni.onSocketError(() => {
            console.log('WebSocket 连接出错');
            this.reconnectWebSocket();
        });
        isConnected = true;
    },

    // 启动 WebSocket 连接的保持活动逻辑
    startWebSocketKeepAlive() {
        setInterval(() => {
            if (isLogOut) {
                return
            }
            if (!isConnected) {
                console.log('尝试重新连接 WebSocket');
                this.connectWebSocket();
                bindChat({
                    client_id: uni.getStorageSync("client_id")
                })
            }
        }, 5000); // 每隔5秒检查 WebSocket 连接状态
    },

    // 重新连接 WebSocket
    reconnectWebSocket() {
        if (isLogOut) {
            return
        }
        if (isReconnecting || isConnected) {
            return; // 如果正在重连或已连接，则不执行
        }

        isReconnecting = true;

        // 执行重连逻辑，可以根据实际需求设置重连的延迟时间
        reconnectTimer = setTimeout(() => {
            this.connectWebSocket();
            // 添加重连时的业务逻辑
            isReconnecting = false; // 重连完成后重置状态
        }, 3000); // 重连延迟时间为3秒，可以根据实际需求进行调整
    },
    // 断开 WebSocket 连接
    disconnectWebSocket() {
        if (socket) {
            socket.close();
            isConnected = false; // 更新连接状态
            clearTimeout(reconnectTimer);
            isLogOut = true
        }
    },

    bindChatIfNeeded() {
        const client_id = uni.getStorageSync("client_id");
        if (client_id) {
            bindChat({
                client_id
            });
        }
    },
};